package eco.tips;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.app.PendingIntent;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent.CanceledException;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView.BufferType;
import eco.tips.EcoTipsWidget.UpdateService;

public class EcoTipsActivity extends ExpandableListActivity {
	private static final String KEY_DESCRIPTION = "description";
	private static final String KEY_TITLE = "title";
	private static final String KEY_CATEGORY = "category";
	int mCurrentTipID = 0;
	ExpandableListView mElvTips = null;
	ExpandableListAdapter mAdapter;

	ArrayList<HashMap<String, String>> categories = new ArrayList<HashMap<String, String>>();
	ArrayList<ArrayList<HashMap<String, String>>> tipGroups = new ArrayList<ArrayList<HashMap<String, String>>>();
	int[][] tipIds = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);

		mElvTips = getExpandableListView();

		loadData();

		mAdapter = new SimpleExpandableListAdapter(this, categories,
				R.layout.group_row, new String[] { KEY_CATEGORY },
				new int[] { R.id.groupname }, tipGroups, R.layout.item_row,
				new String[] { KEY_TITLE, KEY_DESCRIPTION }, new int[] {
						R.id.childTitle, R.id.childDescription });
		mElvTips.setAdapter(mAdapter);
		mElvTips.setItemsCanFocus(true);
		mElvTips.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView list, View item,
					int groupId, int itemId, long arg4) {
				Intent intent = new Intent(EcoTipsActivity.this,
						UpdateService.class);
				intent
						.setAction(android.appwidget.AppWidgetManager.ACTION_APPWIDGET_UPDATE);
				intent.putExtra(EcoTipsWidget.TIP_ID, tipIds[groupId][itemId]);
				try {
					PendingIntent.getService(EcoTipsActivity.this, 0, intent,
							PendingIntent.FLAG_UPDATE_CURRENT).send();
				} catch (CanceledException e) {
					e.printStackTrace();
				}
				finish();
				return true;
			}

		});

		mElvTips.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> adapter, View item,
					int itemId, long arg3) {
				if (mAdapter.getGroupId(itemId) != arg3) {
					Intent i = new Intent(android.content.Intent.ACTION_SEND);
					String title = ((TextView) item
							.findViewById(R.id.childTitle)).getText()
							.toString();
					String description = ((TextView) item
							.findViewById(R.id.childDescription)).getText()
							.toString();

					i.setType("text/plain");
					i.putExtra(Intent.EXTRA_SUBJECT, R.string.app_name);
					i.putExtra(Intent.EXTRA_TEXT, MessageFormat.format(
							"{0}: {1}", title, description));

					startActivity(Intent.createChooser(i, getResources()
							.getText(R.string.lbSend)));
				}
				return true;
			}
		});

		// registerForContextMenu(getExpandableListView());

		Intent intent = getIntent();
		if (intent.getAction().equalsIgnoreCase(UpdateService.OPEN_TIP)) {
			int id = intent.getIntExtra(EcoTipsWidget.TIP_ID, -1);
			mCurrentTipID = (id == -1) ? mCurrentTipID : id;

			boolean stop = false;
			int i = 0, j = 0;
			for (i = 0; i < tipIds.length && !stop; i++)
				for (j = 0; j < tipIds[i].length && !stop; j++)
					stop = (mCurrentTipID == tipIds[i][j]);
			i--;
			j--;

			mElvTips.setSelectedChild(i, j, true);
			mElvTips.expandGroup(i);
			mElvTips.requestLayout();
			mElvTips.setSelection(mCurrentTipID);
		}

		Button btnAbout = (Button) findViewById(R.id.btnAbout);
		btnAbout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				PackageManager manager = EcoTipsActivity.this
						.getPackageManager();
				PackageInfo info = null;
				try {
					info = manager.getPackageInfo(EcoTipsActivity.this
							.getPackageName(), 0);
				} catch (NameNotFoundException e) {
					e.printStackTrace();
				}

				String aboutTemplate = getResources().getString(
						R.string.about_template);
				String name = getString(R.string.app_name);
				String license = getString(R.string.app_license);
				String about = MessageFormat.format(aboutTemplate, name,
						info.versionName, license);

				LinearLayout layout = (LinearLayout) LayoutInflater.from(
						EcoTipsActivity.this).inflate(R.layout.about, null);

				TextView text = (TextView) layout.findViewById(R.id.text);
				text.setText(Html.fromHtml(about), BufferType.SPANNABLE);
				text.setMovementMethod(LinkMovementMethod.getInstance());

				Builder builder = new AlertDialog.Builder(EcoTipsActivity.this)
						.setTitle(
								EcoTipsActivity.this.getResources().getString(
										R.string.app_name)).setView(layout);
				AlertDialog dialog = builder.setIcon(R.drawable.ic_launcher)
						.setPositiveButton(R.string.lbClose, null).show();
				WindowManager.LayoutParams lp = dialog.getWindow()
						.getAttributes();
				lp.dimAmount = 0.0f;
				dialog.getWindow().setAttributes(lp);
				dialog.getWindow().addFlags(
						WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			}
		});

		Button btnExit = (Button) findViewById(R.id.btnExit);
		btnExit.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				finish();
			}
		});

	}

	public void loadData() {
		ArrayList<HashMap<String, String>> tips = null;
		XmlResourceParser parser = getResources().getXml(R.xml.tips);
		String categoryName = "";
		try {
			while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
				if (parser.getEventType() == XmlPullParser.START_TAG) {
					String tagName = parser.getName();
					if (null != tagName && tagName.equalsIgnoreCase("item")) {
						String catName = parser.getAttributeValue(null, "cat");

						if (!categoryName.equalsIgnoreCase(catName)) {
							categoryName = catName;
							HashMap<String, String> c = new HashMap<String, String>();
							c.put(KEY_CATEGORY, categoryName);
							categories.add(c);
							tips = new ArrayList<HashMap<String, String>>();
							tipGroups.add(tips);
						}

						String title = parser.getAttributeValue(null, "title");
						String desc = parser.getAttributeValue(null, "desc");
						HashMap<String, String> t = new HashMap<String, String>();
						t.put(KEY_TITLE, title);
						t.put(KEY_DESCRIPTION, desc);
						tips.add(t);

					}
				}
				parser.next();
			}
			parser.close();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		tipIds = new int[tipGroups.size()][];
		int k = 0;
		for (int i = 0; i < tipGroups.size(); i++) {
			ArrayList<HashMap<String, String>> tipsList = (ArrayList<HashMap<String, String>>) tipGroups
					.get(i);
			tipIds[i] = new int[tipsList.size()];
			for (int j = 0; j < tipsList.size(); j++, k++) {
				tipIds[i][j] = k;
			}
		}
	}
}